package com.example.batch.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableConfigurationProperties(BatchProperties.class)
@ConditionalOnProperty(prefix = "spring.batch.process", name = "enabled", havingValue = "true")
public class BatchProcessAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public AsyncJobLauncher asyncJobLauncher(JobRepository jobRepository, 
            ThreadPoolTaskExecutor batchTaskExecutor) throws Exception {
        AsyncJobLauncher launcher = new AsyncJobLauncher();
        launcher.setJobRepository(jobRepository);
        launcher.setTaskExecutor(batchTaskExecutor);
        return launcher;
    }

    @Bean
    @ConditionalOnMissingBean
    public ThreadPoolTaskExecutor batchTaskExecutor(BatchProperties properties) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(properties.getThread().getCoreSize());
        executor.setMaxPoolSize(properties.getThread().getMaxSize());
        executor.setQueueCapacity(properties.getThread().getQueueCapacity());
        executor.setThreadNamePrefix("batch-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    @Bean
    @ConditionalOnMissingBean
    public BatchJobBuilderFactory batchJobBuilderFactory(
            List<ItemReader<?>> readers,
            List<ItemProcessor<?, ?>> processors,
            List<ItemWriter<?>> writers,
            BatchProperties properties) {
        return new BatchJobBuilderFactory(readers, processors, writers, properties);
    }
} 